import { gameMain } from "../GameMain";
import { querySql } from "../../../common/db";
import { RpcCallRes, RpcHandler, RpcHandlerProxy } from "kilom";
import { Xlsx } from "../../../config/Xlsx";

export default class RpcGameLogin extends RpcHandler {

    /**
     * 获取账号在本服的玩家id 0为还没创角
     * @param user 
     * @returns 
     */
    async getPid(user: string): Promise<RpcCallRes<number>> {
        try {
            let res = await querySql("select `pid` from `player` where `sid` = ? and `user` = ?", [gameMain.sid, user]);
            if (res.length) {
                let player = gameMain.playerDic[res[0].pid];
                if (player) {
                    //顶号
                    console.log("顶号");
                    gameMain.delPlayer(player.pid);
                    await this.app.rpc(player.frontSid).connector.main.kick(player.pid);
                }
                return { data: res[0].pid };
            }
            return { data: 0 };
        } catch (err) {
            return { err: { code: -1, msg: (err as Error).message } };
        }
    }

    /**
     * 获取账号在本服的玩家id 0为还没创角
     * @param user 
     * @returns 
     */
    async createRole(user: string, name: string, career: number): Promise<RpcCallRes<number>> {
        try {
            if (!Xlsx.career.get(career)) return { err: { code: -1, msg: "非法职业id" } };
            let res = await querySql("select `pid` from `player` where `sid` = ? and `user` = ?", [gameMain.sid, user]);
            if (res.length) return { err: { code: -1, msg: "该账号已创角" } };
            res = await querySql("select `pid` from `player` where `sid` = ? and `name` = ?", [gameMain.sid, name]);
            if (res.length) return { err: { code: -1, msg: "游戏名已存在" } };
            let pid = gameMain.sid * 100000 + gameMain.total;
            let date = new Date();
            res = await querySql("insert into `player`(`pid`,`sid`,`user`,`name`,`career`,`createTime`,`lastLoginTime`,`lastLogoutTime`) values (?,?,?,?,?,?,?,?)",
                [pid, gameMain.sid, user, name, career, date, date, date]);
            if (res.affectedRows != 1) return { err: { code: -1, msg: "操作失败" } };
            gameMain.total++;
            return { data: pid };
        } catch (err) {
            return { err: { code: -1, msg: (err as Error).message } };
        }
    }

}

declare global {
    interface IRpcGame {
        login: RpcHandlerProxy<RpcGameLogin>
    }
}